use crate::config::CONFIG;
use sqlx::{Error, Executor, MySql, MySqlPool, Pool};

pub async fn get_pool() -> Result<Pool<MySql>, Error>{
    let config = CONFIG.get_mysql();
    let url = format!("mysql://{}:{}@{}:{}/{}", config.username, config.password, config.host, config.port, config.database);
    match MySqlPool::connect(url.as_str()).await {
        Ok(pool) => {
            Ok(pool)
        }
        Err(err) => {
            println!("{}", err);
            Err(err)
        }
    }
}

pub async fn insert(sql: String) {
    let pool = match get_pool().await {
        Ok(pool) => pool,
        _ => {
            return;
        }
    };
    match sqlx::query(sql.as_str()).execute(&pool).await {
        Ok(ok) => {
            if ok.rows_affected() > 0 {
                println!("插入数据成功！");
            } else {
                println!("插入数据失败！");
            }
        }
        Err(_) => {
            println!("插入数据失败！");
        }
    }
}